package cn.amossun.starter.event.handler;

import cn.amossun.starter.event.common.Constants;
import cn.amossun.starter.event.property.EventContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.InitializingBean;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class EventQueuesInitializer implements InitializingBean {

    private EventContext eventContext;

    private RabbitAdmin rabbitAdmin;

    public EventQueuesInitializer(EventContext eventContext, RabbitAdmin rabbitAdmin) {
        this.eventContext = eventContext;
        this.rabbitAdmin = rabbitAdmin;
    }

    Map<String, Object> buildArgs() {
        Map<String, Object> args = new HashMap<>(2);
        args.put("x-dead-letter-exchange", Constants.EVENT_DEAD_EXCHANGE);
        args.put("x-dead-letter-routing-key", Constants.EVENT_DEAD_ROUTING_KEY);
        return args;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initialize();
    }

    void initialize() {
        eventContext.getQueueContexts().stream().forEach(eventQueue -> {
            Queue queue = new Queue(eventQueue.getQueueName(), eventQueue.isDurable(), eventQueue.isExclusive(), eventQueue.isAutoDelete(), buildArgs());
            rabbitAdmin.declareQueue(queue);
            eventQueue.setQueue(queue);
        });
    }

}
